package com.tianxinweb.controller;

import com.tianxinweb.config.UploadConfig;
import com.tianxinweb.entity.Result;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by cboy on 2018/7/24.
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    private final static Logger logger = LoggerFactory.getLogger(ImageController.class);

    @Autowired
    private UploadConfig uploadConfig;

    /**
     * 上传图片到临时目录或者富文本图片上传
     * @param type 默认普通文件上传，其他表示富文本图片上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public Result addImage(@RequestParam("file") MultipartFile file,@RequestParam(value = "type",defaultValue = "0") Integer type) {

        if(file.getSize()>2048000){//文件不能大于2M
            throw new MyException(ResultEnum.FILE_SIZE_ERROR);
        }
        String imgIype = "image/bmp image/gif image/jpeg image/png";
        if(imgIype.indexOf(file.getContentType())<0){//文件格式不正确
            throw new MyException(ResultEnum.FILE_FORMAT_ERROR);
        }
        String originalName = file.getOriginalFilename();
        String suffix = originalName.substring(originalName.lastIndexOf("."),originalName.length());
        String suffixStr = ".gif.jpg.jpeg.bmp.png.GIF.JPG.JPEG.BMP.PNG";
        if(suffixStr.indexOf(suffix)<0){//文件后缀不正确
            throw new MyException(ResultEnum.FILE_FORMAT_ERROR);
        }
        String rootPath = "";
        String filename = "";
        if(type==0){
            rootPath = uploadConfig.getPath()+"/temp";
            filename = new SimpleDateFormat("yyyyMM").format(new Date())+"/"+ UUID.randomUUID().toString()+suffix;
        }else{
            rootPath = uploadConfig.getPath()+"/editor";
            filename = new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+ UUID.randomUUID().toString()+suffix;
        }

        File path = new File(rootPath,filename);
        if(!path.getParentFile().exists()){
            path.getParentFile().mkdirs();
        }
        try {
            file.transferTo(path);
            return Result.success().add("path",filename);
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new MyException(ResultEnum.FAILE);
        }
    }

}
